package com.jhgsys.internal.dict.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.MenuTree;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.dto.DictItemDto;
import com.jhgsys.internal.dict.entity.DictItem;
import com.jhgsys.internal.dict.mapper.DictItemMapper;
import com.jhgsys.internal.dict.service.IDictItemService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务字典项 Service实现
 *
 * @author chenweihua
 * @date 2020-05-22 15:28:32
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItem> implements IDictItemService {

    /**
     * 查询（分页）
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param request QueryRequest
     * @param dictItem dictItem
     * @return IPage<DictItem>
     */
    @Override
    public IPage<DictItem> findDictItems(QueryRequest request, DictItem dictItem) {
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotEmpty(dictItem.getDictCode())) {
            queryWrapper.eq(DictItem::getDictCode, dictItem.getDictCode());
        }
        if (StringUtils.isNotEmpty(dictItem.getItemName())) {
            queryWrapper.like(DictItem::getItemName, dictItem.getItemName());
        }
        Page<DictItem> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询（所有）
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param dictItem dictItem
     * @return List<DictItem>
     */

    @DS("second")
    @Override
    public List<DictItemDto> findDictItems(DictItem dictItem) {
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictItem::getItemStatus, FebsConstant.ENABLE);
        if (StringUtils.isNotEmpty(dictItem.getDictCode())) {
            queryWrapper.eq(DictItem::getDictCode, dictItem.getDictCode());
        }
        if (StringUtils.isNotEmpty(dictItem.getItemName())) {
            queryWrapper.eq(DictItem::getItemName, dictItem.getItemName());
        }
        queryWrapper.orderByAsc(DictItem::getSortNum);
        List<DictItem> dictItemList = this.baseMapper.selectList(queryWrapper);
        List<DictItemDto> returnList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dictItemList)) {
            returnList = dictItemList.stream().map(d -> BeanHelper.copyProperties(d, DictItemDto.class)).collect(Collectors.toList());
        }
        return returnList;
    }

    /**
     * 根据ID查询
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param id
     * @return DictItem
     */
    @Override
    public DictItem findDictItemById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param dictItem dictItem
     */
    @Override
    @Transactional
    public void createDictItem(DictItem dictItem) {
        this.save(dictItem);
    }

    /**
     * 修改
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param dictItem dictItem
     */
    @Override
    @Transactional
    public void updateDictItem(DictItem dictItem) {
        this.saveOrUpdate(dictItem);
    }

    /**
     * 逻辑删除
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param dictItem dictItem
     * @param dictItemIds dictItemIds
     */
    @Override
    @Transactional
    public void deleteDictItem(DictItem dictItem,String dictItemIds) {
        List<String> list = Arrays.asList(dictItemIds.split(StringPool.COMMA));
        this.baseMapper.update(dictItem,new LambdaQueryWrapper<DictItem>().in(DictItem::getItemId,list));
    }

    /**
     * 物理删除
     * @author chenweihua
     * @date 2020-05-22 15:28:32
     * @param dictItemIds dictItemIds
     */
    @Override
    @Transactional
    public void physicallyDeleteDictItem(String dictItemIds) {
        List<String> list = Arrays.asList(dictItemIds.split(StringPool.COMMA));
        LambdaQueryWrapper<DictItem> wapper = new LambdaQueryWrapper<>();
        wapper.in(DictItem::getItemId,list);
        this.remove(wapper);
    }

    @Override
    public void saveDictItemBatch(List<DictItem> dictItems) {
        this.saveBatch(dictItems);
    }

    @Override
    public void deleteByDictCode(String dictCode) {
        this.baseMapper.delete(new LambdaQueryWrapper<DictItem>().eq(DictItem::getDictCode,dictCode));
    }

    @Override
    public List<MenuTree<DictItem>> findDictes() {
        //1：行业类型
        List<DictItem> dicts = this.baseMapper.selectList(new QueryWrapper<DictItem>().lambda()
                .eq(DictItem::getDictCode,"3000"));
        List<MenuTree<DictItem>> returnDatas = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(dicts)){
            //父元素集合
            for (DictItem dictitem : dicts){
                MenuTree<DictItem> deptHead = new MenuTree<>();
                deptHead.setName(dictitem.getItemName());
                deptHead.setValue(dictitem.getItemCode());
                //循环添加子元素
                List<DictItem> dictitems = this.baseMapper.selectList(new QueryWrapper<DictItem>().lambda()
                        .eq(DictItem::getDictCode,dictitem.getItemCode()));
                //子元素集合
                List<MenuTree<DictItem>> dictTree = new ArrayList<>();
                for(DictItem dictitemes : dictitems){
                    MenuTree<DictItem> tree = new MenuTree<>();
                    tree.setName(dictitemes.getItemName());
                    tree.setValue(dictitemes.getItemCode());
                    dictTree.add(tree);
                }
                deptHead.setChilds(dictTree);
                returnDatas.add(deptHead);
            }
        }
        return returnDatas;
    }

    @Override
    public List<DictItem> findByItemIds(List<String> itemIds){
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictItem::getDeletedFlg, FebsConstant.VALID);
        queryWrapper.in(DictItem::getItemId,itemIds);
        return this.baseMapper.selectList(queryWrapper);
    }

}
